package com.yulang.security.core.config;

import com.yulang.security.core.filter.MobileAuthencationFilter;
import com.yulang.security.core.handler.CustomAuthenticationFailHandler;
import com.yulang.security.core.handler.CustomAuthenticationSuccessHandler;
import com.yulang.security.core.provider.MobileAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

/**
 * 用于组合手机号登录相关的类
 */

@Component
public class MobileAuthenticationConfig
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private CustomAuthenticationSuccessHandler successHandler;

    @Autowired
    private CustomAuthenticationFailHandler failHandler;

    @Qualifier("mobileUserDetailsService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        MobileAuthencationFilter filter = new MobileAuthencationFilter();
        //从共享对象中获取AuthenticationManager
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        filter.setRememberMeServices(http.getSharedObject(RememberMeServices.class));
        //添加成功和失败的处理器
        filter.setAuthenticationSuccessHandler(successHandler);
        filter.setAuthenticationFailureHandler(failHandler);

        //同一账号使用名字和密码都只能在一个地方登录
        filter.setSessionAuthenticationStrategy(http.getSharedObject(SessionAuthenticationStrategy.class));

        MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);

        http.authenticationProvider(provider)
                .addFilterAfter(filter,UsernamePasswordAuthenticationFilter.class);

    }
}
